//
//  IntroViewController.m
//  Brand
//
//  Created by Faker on 4/8/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "IntroViewController.h"
#import "CollectionFixedHeaderLayout.h"
#import "PersonDetailVC.h"
#import "WYDetailVC.h"
#import "NewsDetailVC.h"
#import "iCarousel.h"
#import "VideoObj.h"
#import "VideoInfoVC.h"
#import "IntroObj.h"
#import "NZAlertView.h"
#import "Header.h"
#import "config.h"

#define CellIdentifer   @"CellIdentifer"

@interface IntroViewController ()
@property (weak, nonatomic) IBOutlet UIView *navTopContentView;
@property (weak, nonatomic) IBOutlet UITableView *myTableView;

#pragma mark - 影片介绍
@property (strong, nonatomic) iCarousel* myIcarousel;
@property (strong, nonatomic) NSArray* filmArray;
@property (strong, nonatomic) UIImageView* myImageView;

#pragma mark - 人物
@property (strong, nonatomic) UICollectionView* personCollectionView;
@property (strong, nonatomic) NSMutableArray* personArray;

#pragma mark - 世界观
@property (strong, nonatomic) UICollectionView* worldCollectionView;
@property (strong, nonatomic) NSArray* worldArray;

#pragma mark - 纹耀
@property (strong, nonatomic) UICollectionView* wenYaoCollectionView;
@property (strong, nonatomic) NSArray* wenYaoArray;

#pragma mark - 国家
@property (strong, nonatomic) UICollectionView* countryCollectionView;
@property (strong, nonatomic) NSArray* countryArray;

#pragma mark - 种族
@property (strong, nonatomic) UICollectionView* ethCollectionView;
@property (strong, nonatomic) NSArray* raceArray;

#pragma mark - 道具
@property (strong, nonatomic) UICollectionView* propsCollectionView;
@property (strong, nonatomic) NSArray* propsArray;


@property (strong, nonatomic) NSArray* titleArray;
@property (strong, nonatomic) NSArray* allDataArray;
@property (strong, nonatomic) NSArray* fakerDataArray;
@property (strong, nonatomic) NSArray* allCollectionArray;



@end

@implementation IntroViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.titleArray = @[@"影片介绍",@"人物",@"世界观",@"纹耀",@"国家",@"种族",@"道具"];
        if(![[kHandle sharedInstance] isShowTrueView])
        {
            self.titleArray = @[@"人物",@"世界观",@"纹耀",@"国家",@"种族",@"道具"];
        }
        self.allDataArray = [[NSMutableArray alloc]init];
        self.fakerDataArray = [[NSArray alloc]init];
        self.allCollectionArray = [[NSMutableArray alloc]init];
        self.personArray = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self drawNavTopContentView:self.navTopContentView];
    [self setUp];
}

-(void)setUp
{
    
    CGRect rect = CGRectMake(0, 0, 320, 138);
    
    self.myIcarousel = [[iCarousel alloc]initWithFrame:CGRectMake(10, 0, 300, 160)];
    self.myIcarousel.delegate = self;
    self.myIcarousel.dataSource = self;
    self.myIcarousel.decelerationRate=.2;   //滑动需要用多大的力气才能切换到下一个。。
    //[self.myIcarousel setPerspective:-0.002]; //这个是控制两张图之间的间距和倾斜度的
    //self.myIcarousel.perspective = -0.005;
    self.myIcarousel.type=iCarouselTypeCoverFlow;

    
    
    self.personCollectionView = [self drawCollectionViewWithFrame:rect andFlowLayout:[self getFlowLayoutWithIsCircle:YES ] andTag:0];
    [self registerCellAndHeaderForCollectionView:self.personCollectionView andWithIsCircle:YES];
    
    self.worldCollectionView = [self drawCollectionViewWithFrame:rect andFlowLayout:[self getFlowLayoutWithIsCircle:NO] andTag:1];
    [self registerCellAndHeaderForCollectionView:self.worldCollectionView andWithIsCircle:NO];
    
    self.wenYaoCollectionView = [self drawCollectionViewWithFrame:rect andFlowLayout:[self getFlowLayoutWithIsCircle:YES] andTag:2];
    [self registerCellAndHeaderForCollectionView:self.wenYaoCollectionView andWithIsCircle:YES];
    
    self.countryCollectionView = [self drawCollectionViewWithFrame:rect andFlowLayout:[self getFlowLayoutWithIsCircle:NO] andTag:3];
    [self registerCellAndHeaderForCollectionView:self.countryCollectionView andWithIsCircle:NO];
    
    self.ethCollectionView = [self drawCollectionViewWithFrame:rect andFlowLayout:[self getFlowLayoutWithIsCircle:YES] andTag:4];
    [self registerCellAndHeaderForCollectionView:self.ethCollectionView andWithIsCircle:YES];
    
    self.propsCollectionView = [self drawCollectionViewWithFrame:rect andFlowLayout:[self getFlowLayoutWithIsCircle:NO] andTag:5];
    [self registerCellAndHeaderForCollectionView:self.propsCollectionView andWithIsCircle:NO];
    
    self.allCollectionArray = @[self.personCollectionView,self.worldCollectionView,self.wenYaoCollectionView,self.countryCollectionView,self.ethCollectionView,self.propsCollectionView];
    
    [self prepareGetData];
}

#pragma mark - 网络请求

-(void)prepareGetData
{
    [kApp displayWaitViewWithAllMaskView:NO];
    
    NSString* url = [NSString stringWithFormat:@"%@Api&a=getKBIntro",API_BASE];
   
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self getDataSuccess:responseObj];
        }
        else{
        
            [self getDataError];
            
        }
    }];
    
}

-(void)getDataSuccess:(id)responseObj
{
    [kApp hideWaitView];
    
    NSDictionary* dic = (NSDictionary*)responseObj;
    [UserDataBasic setObject:dic forKey:LocalIntroData];
    [self handleDataWithDict:dic];
   
}

-(void)getDataError
{
    [kApp hideWaitView];
    [PopTips tips:self.view Msg:NotifyNoNet];
    
    NSDictionary* dic = [UserDataBasic getObjectForKey:LocalIntroData];
    if(IsNull(dic))
    {
        [self performSelector:@selector(goBack:) withObject:self afterDelay:0.7];
      return;
    }
    else{
        [self handleDataWithDict:dic];
    }
}

- (void)NZAlertViewDidDismiss:(NZAlertView *)alertView
{
    [self goBack:nil];
}

-(void)handleDataWithDict:(NSDictionary*)dic
{
    self.filmArray = [dic objectForKey:@"movie"];
    NSArray* tempArray = [dic objectForKey:@"people"];
    for (NSDictionary* cur in tempArray) {
        IntroObj* introObj = [[IntroObj alloc]init];
        introObj.title = [cur objectForKey:@"title"];
        introObj.content = [cur objectForKey:@"content"];
        introObj.pic = [cur objectForKey:@"pic"];
        introObj.picArray= [cur objectForKey:@"page_pic"];
        [self.personArray addObject:introObj];
    }
    self.worldArray = [dic objectForKey:@"worldview"];
    self.wenYaoArray = [dic objectForKey:@"medal"];
    self.countryArray = [dic objectForKey:@"country"];
    self.raceArray = [dic objectForKey:@"race"];
    self.propsArray = [dic objectForKey:@"item"];
    self.allDataArray = @[self.personArray,self.worldArray,self.wenYaoArray,self.countryArray,self.raceArray,self.propsArray];
    
    [self.myTableView reloadData];
}

#pragma mark - iCarousel methods
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    return [self.filmArray count];
    
}

- (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel
{
    return 3;
}


- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
	//create new view if no view is available for recycling
	if (view == nil) //如果没有可以重用的
	{
        view = [[[NSBundle mainBundle] loadNibNamed:@"IcarouselCell" owner:self options:nil] objectAtIndex:0];
        
    }
    UILabel* titleLabel = (UILabel*)[view viewWithTag:200];
    UIImageView* imageView = (UIImageView*)[view viewWithTag:302];
    titleLabel.text = [[self.filmArray objectAtIndex:index] objectForKey:@"title"];
    [[AFGetData sharedInstance] initSDWebImage:[[self.filmArray objectAtIndex:index] objectForKey:@"pic"] andTrueImageView:imageView andPlaceholderImage:nil];
    view.layer.cornerRadius = 2;
	return view;
}

-(void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index{
    
    NSDictionary* dic = [self.filmArray objectAtIndex:index];
   
    VideoObj* videoObj = [[VideoObj alloc]init];
    videoObj.episodeId = [dic objectForKey:@"id"];
    videoObj.contentName = [dic objectForKey:@"title"];
    
    VideoInfoVC* infoVC = [[VideoInfoVC alloc]initWithNibName:@"VideoInfoVC" bundle:nil];
    infoVC.videoObj = videoObj;
    
    if(index == carousel.currentItemIndex)
    {
        [self.navigationController pushViewController:infoVC animated:YES];
    }
    
    
    
}

-(BOOL)carousel:(iCarousel *)carousel shouldSelectItemAtIndex:(NSInteger)index
{
    return YES;
}

//可不可以循环滚动
-(BOOL)carouselShouldWrap:(iCarousel *)carousel
{
    return YES;
}

//每个item的间隔宽度
- (CGFloat)carouselItemWidth:(iCarousel *)carousel
{
    //usually this should be slightly wider than the item views
    return 150; //每一项的宽度
}

-(CGFloat)carousel:(iCarousel *)carousel valueForTransformOption:(iCarouselTranformOption)option withDefault:(CGFloat)value
{
    return 0.45;
}


-(void)carouselDidEndScrollingAnimation:(iCarousel *)carousel
{
   
    [self addGoldBorder];
}

-(void)addGoldBorder
{
    
    UIView* currentView = [self.myIcarousel currentItemView];
  
    [currentView addSubview:self.myImageView];
    
    NSArray* visibleViews = [self.myIcarousel visibleItemViews];
    
    for (UIView* cusView in visibleViews) {
        UIView* shadeView = (UIView*)[cusView viewWithTag:202];
        UIImageView* imageView = (UIImageView*)[cusView viewWithTag:303];
        if(cusView == currentView)
        {
            imageView.hidden = NO;
            shadeView.hidden = YES;
        }
        else{
            imageView.hidden = YES;
            shadeView.hidden = NO;
        }
    }
}


#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.titleArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* identifier = @"identifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //每次都要清掉所有的子视图
    if(cell == nil)
    {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"IntroCell" owner:self options:nil]lastObject];
        
    }
    UIView* tempView = (UIView*)[cell.contentView viewWithTag:100];
    [tempView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    UIImageView* imageView = (UIImageView*)[cell.contentView viewWithTag:302];

    if(indexPath.section == 0)
    {
        imageView.hidden = YES;
        tempView.clipsToBounds = NO;
        cell.clipsToBounds = NO;
    }
    
    else if(indexPath.section == 1)
    {
        imageView.hidden = YES;
        
    }
    else if(indexPath.section == 2){
        imageView.hidden = NO;
        
    }
    else if(indexPath.section == 3)
    {
        imageView.hidden = YES;
       
    }
    else if(indexPath.section == 4)
    {
        imageView.hidden = NO;
        
    }
    else if (indexPath.section == 5)
    {
        imageView.hidden = YES;
        
    }
    else
    {
        imageView.hidden = NO;
    }
    
    if([[kHandle sharedInstance] isShowTrueView]) {
        if(indexPath.section!=0)
        {
            UICollectionView* tempCollectionView = [self.allCollectionArray objectAtIndex:indexPath.section-1];
            [tempView addSubview:tempCollectionView];
            [tempCollectionView reloadData];
        }
        else{
            
            [tempView addSubview:self.myIcarousel];
            [self.myIcarousel reloadData];
        }

    } else {
        UICollectionView* tempCollectionView = [self.allCollectionArray objectAtIndex:indexPath.section];
        [tempView addSubview:tempCollectionView];
        [tempCollectionView reloadData];
    }
    
    
        cell.backgroundColor = [UIColor clearColor];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0)
    {
        return 160;
    }
    return 138;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* headerView = [[[NSBundle mainBundle]loadNibNamed:@"HeaderCell" owner:self options:nil]lastObject];
    UILabel* titleLabel = (UILabel*)[headerView viewWithTag:200];
    titleLabel.text = [self.titleArray objectAtIndex:section];
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}


#pragma mark - UICollectionViewDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    int tag = collectionView.tag;
    if(IsNull(self.allDataArray)||self.allDataArray.count==0)
    {
        return 0;
    }
    else{
        return [[self.allDataArray objectAtIndex:tag] count];
    }
    
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier =CellIdentifer;
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    NSArray* tempArray = [self.allDataArray objectAtIndex:collectionView.tag];
    
    UILabel *titleLabel=(UILabel *)[cell viewWithTag:200];
    UIImageView* imageView = (UIImageView*)[cell viewWithTag:302];
    UIImageView* fakeImage = (UIImageView*)[cell viewWithTag:301];
    
    
    if(collectionView == self.wenYaoCollectionView)
    {
        fakeImage.hidden = YES;
    }
    else{
        fakeImage.hidden = NO;
    }
    
    if(collectionView == self.personCollectionView || collectionView==self.wenYaoCollectionView || collectionView == self.ethCollectionView)
    {
        imageView.layer.cornerRadius = imageView.width/2;
        imageView.clipsToBounds = YES;
        
    }
    if(collectionView == self.personCollectionView)
    {
        IntroObj* introObj = [self.personArray objectAtIndex:indexPath.row];
        titleLabel.text = introObj.title;
        [[AFGetData sharedInstance] initSDWebImage:introObj.pic andTrueImageView:imageView andPlaceholderImage:nil];
    }
    else{
    
        NSDictionary* dic = [tempArray objectAtIndex:indexPath.row];
        titleLabel.text = [dic objectForKey:@"title"];
        [[AFGetData sharedInstance] initSDWebImage:[dic objectForKey:@"pic"] andTrueImageView:imageView andPlaceholderImage:nil];
    }
    
    

   
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(collectionView == self.personCollectionView)
    {
        PersonDetailVC* detailVC = [[PersonDetailVC alloc]initWithNibName:@"PersonDetailVC" bundle:nil];
       
        detailVC.dataArray = self.personArray;
        detailVC.currentItemIndex = indexPath.row;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    else if(collectionView == self.wenYaoCollectionView)
    {
        WYDetailVC* wyVC = [[WYDetailVC alloc]initWithNibName:@"WYDetailVC" bundle:nil];
        wyVC.dataArray = self.wenYaoArray;
        wyVC.currentItemIndex = indexPath.row;
        [self.navigationController pushViewController:wyVC animated:YES];
    }
    else
    {
         NewsDetailVC* detailVC = [[NewsDetailVC alloc]initWithNibName:@"NewsDetailVC" bundle:nil];
        int tag = collectionView.tag;
        NSDictionary* dic = [[self.allDataArray objectAtIndex:tag] objectAtIndex:indexPath.row];
         NSMutableArray* tempArray = [NSMutableArray array];
        switch (tag) {
            case 1:
                detailVC.title = @"世界观";
                detailVC.dataArray = self.worldArray;
               break;
            case 3:
                detailVC.title = @"国家";
               
                for (NSDictionary* cur in self.countryArray) {
                    if([[cur objectForKey:@"open_state"] isEqualToString:@"1"])
                    {
                        [tempArray addObject:cur];
                    }
                }
                detailVC.dataArray = tempArray;
                break;
             case 4:
                detailVC.title = @"种族";
                detailVC.dataArray = self.raceArray;
                break;
            case 5:
                detailVC.title = @"道具";
                detailVC.dataArray = self.propsArray;
            default:
                break;
        }
       
       
        if(collectionView == self.countryCollectionView)
        {
            NSString* status = [dic objectForKey:@"open_state"];
            if([status isEqualToString:@"0"])
            {
                NZAlertView *alert = [[NZAlertView alloc] initWithStyle:NZAlertStyleInfo
                                                                  title:NotifyNormal
                                                                message:NotifyVideoNotDownButDel
                                                               delegate:nil];
                [alert show];
                return;

            }
        }
          detailVC.currentItemIndex = indexPath.row;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}


#pragma mark - UIScrollViewDelegat
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView == self.myTableView)
    {
        [Common tableHeaderScrollWithScrollView:self.myTableView andWithHeaderHeight:40];
    }
}

#pragma mark - 生成collectionview和布局布局管理器
-(UICollectionView*)drawCollectionViewWithFrame:(CGRect)frame andFlowLayout:(CollectionFixedHeaderLayout*)flowLayout andTag:(int)tag
{
    UICollectionView* myCollectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    myCollectionView.showsVerticalScrollIndicator = NO;
    myCollectionView.showsHorizontalScrollIndicator = NO;
    myCollectionView.dataSource = self;
    myCollectionView.delegate = self;
    myCollectionView.backgroundColor = [UIColor clearColor];
    myCollectionView.clipsToBounds = NO;
    myCollectionView.tag = tag;
    return myCollectionView;
}

-(void)registerCellAndHeaderForCollectionView:(UICollectionView*)collectionView andWithIsCircle:(BOOL)isCircle
{
    UINib *cellNib = nil;
    if(isCircle)
    {
        cellNib = [UINib nibWithNibName:@"collectionCell" bundle:nil];
    }
    else{
        cellNib = [UINib nibWithNibName:@"SquareCollectionCell" bundle:nil];
    }
    
    [collectionView registerNib:cellNib forCellWithReuseIdentifier:CellIdentifer];
    
}

//一个布局管理器只能对应一个collectionView
-(CollectionFixedHeaderLayout*)getFlowLayoutWithIsCircle :(BOOL)isCircle
{
    CollectionFixedHeaderLayout *flowLayout = [[CollectionFixedHeaderLayout alloc] init];
    flowLayout.isFiexed = NO;
    if(isCircle) //圆角
    {
        [flowLayout setItemSize:CGSizeMake(122, 138)];
    }
    else{
    
        [flowLayout setItemSize:CGSizeMake(140, 110)];
    }
    
    flowLayout.minimumInteritemSpacing =0;
    flowLayout.minimumLineSpacing = 6;
    //flowLayout.headerReferenceSize = CGSizeMake(320, 30);
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    if(isCircle)
    {
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);  //top left bottom right
    }
    else{
        flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    }
    return flowLayout;
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)goBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
